<template>
  <view class="container">
    <!-- 头部搜索 -->
    <view class="search-box">
      <view class="search-input">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input type="text" placeholder="搜索公司名称、行业或职位..." v-model="searchKeyword" @confirm="toSearch"/>
      </view>
      <button class="search-btn" @click="toSearch">搜索</button>
    </view>
    
    <!-- 轮播图 -->
    <view class="banner">
      <uni-swiper-dot :current="current" :number="3" mode="round" class="dots">
        <swiper 
          class="swiper" 
          @change="changeSwiper"
          indicator-dots
          autoplay
          circular>
          <swiper-item v-for="(item, index) in banners" :key="index">
            <image :src="item.imgUrl" mode="widthFix" class="banner-img"></image>
          </swiper-item>
        </swiper>
      </uni-swiper-dot>
    </view>
    
    <!-- 功能入口 -->
    <view class="functions">
      <view class="func-item" @click="toCompanySearch">
        <img src="@/static/icons/search-bar.png" alt="" />
        <text class="func-text">公司查询</text>
      </view>
      <view class="func-item" @click="toAiAssistant">
        <img src="@/static/icons/section.png" alt="" />
        <text class="func-text">AI助手</text>
      </view>
      <view class="func-item" @click="toNews">
        <img src="@/static/icons/goods-nav.png" alt="" />
        <text class="func-text">职场资讯</text>
      </view>
      <view class="func-item" @click="toPublishReview">
         <img src="@/static/icons/combox.png" alt="" />
        <text class="func-text">发布评价</text>
      </view>
    </view>
    
    <!-- 热门公司 -->
    <view class="section">
      <view class="section-title">
        <text class="title-text">热门公司</text>
        <text class="more" @click="toMoreCompanies">更多</text>
      </view>
      <view class="company-list">
        <view class="company-item" v-for="(company, index) in hotCompanies" :key="index" @click="toCompanyDetail(company.id)">
          <image :src="company.logoUrl" mode="widthFix" class="company-logo"></image>
          <view class="company-info">
            <view class="company-name">{{ company.name }}</view>
            <view class="company-rating">
              <uni-icons type="star" size="14" color="#FFCC00"></uni-icons>
              <text class="rating-num">{{ company.rating.toFixed(1) }}</text>
              <text class="review-count">({{ company.reviewCount }}条评价)</text>
            </view>
            <view class="company-tags">
              <text class="tag" v-for="(tag, i) in company.tags" :key="i">{{ tag }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 最新评价 -->
    <view class="section">
      <view class="section-title">
        <text class="title-text">最新评价</text>
        <text class="more" @click="toAllReviews">更多</text>
      </view>
      <view class="review-list">
        <view class="review-item" v-for="(review, index) in latestReviews" :key="index">
          <view class="review-header">
            <image :src="review.userAvatar" mode="widthFix" class="user-avatar"></image>
            <view class="user-info">
              <text class="user-name">{{ review.userName }}</text>
              <text class="review-time">{{ review.time }}</text>
            </view>
            <text class="company-name">{{ review.companyName }}</text>
          </view>
          <view class="review-content">
            <text>{{ review.content }}</text>
          </view>
          <view class="review-metrics">
            <view class="metric-item">
              <uni-icons type="thumbs-up" size="16" color="#999"></uni-icons>
              <text>点赞：{{ review.likes }}</text>
            </view>
            <view class="metric-item">
              <uni-icons type="comment" size="16" color="#999"></uni-icons>
              <text>评论：{{ review.comments }}</text>
            </view>
            <view class="metric-item">
              <uni-icons type="star" size="16" color="#FFCC00"></uni-icons>
              <text>打分：{{ review.score }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserReviews, getReviewRatings, getCompanyList,getCompanyOverallScore,getCompanyDetail } from '@/api/company.js';

export default {
  data() {
    return {
      searchKeyword: '',
      current: 0,
      banners: [
        { imgUrl: '/static/image/banner1.png', link: '' },
        { imgUrl: '/static/image/banner2.png', link: '' },
        { imgUrl: '/static/image/banner3.png', link: '' }
      ],
      hotCompanies: [], // 将从接口获取
      latestReviews: [],
    };
  },
  onLoad() {
    this.loadLatestReviews();
    this.loadHotCompanies();
  },
  methods: {
    // 计算综合评分
    calculateAverageScore(ratings) {
      if (!ratings || ratings.length === 0) return 0;
      const total = ratings.reduce((sum, rating) => sum + parseFloat(rating.score || 0), 0);
      return (total / ratings.length).toFixed(1);
    },
    
    // 获取单个评价的综合评分
    async getReviewAverageScore(reviewId) {
      try {
        const res = await getReviewRatings(
		{ 
			reviewId,
			pageNum:1,
			pageSize:10 
		}
		);
        if (res && res.rows && res.rows.length > 0) {
          return this.calculateAverageScore(res.rows);
        }
      } catch (error) {
        console.error(`获取评价 ${reviewId} 的综合评分失败:`, error);
      }
      return 0;
    },
    
    // 获取企业综合评分
    async getCompanyRating(companyId) {
      try {
        const res = await getCompanyOverallScore({
          companyId,
          pageNum: 1,
          pageSize: 1
        });
        if (res && res.data) {
          let data = res.data;
          // 处理不同可能的数据结构
          if (!Array.isArray(data)) {
            if (data.list) data = data.list;
            else if (data.rows) data = data.rows;
            else return 0;
          }
          
          // 查找综合评分
          if (data.length > 0 && data[0].overallScore !== undefined) {
            return parseFloat(data[0].overallScore);
          }
        }
      } catch (error) {
        console.error(`获取企业 ${companyId} 的综合评分失败:`, error);
      }
      return 0;
    },
    
    // 获取企业评价数量
    async getCompanyReviewCount(companyId) {
      try {
        const res = await getUserReviews({
          companyId,
          pageNum: 1,
          pageSize: 1
        });
        if (res && res.total !== undefined) {
          return res.total;
        } else if (res && res.rows) {
          return res.rows.length;
        }
      } catch (error) {
        console.error(`获取企业 ${companyId} 的评价数量失败:`, error);
      }
      return 0;
    },
    
    // 加载热门公司
    async loadHotCompanies() {
      try {
        const params = {
          pageNum: 1,
          pageSize: 3 // 获取前3家公司作为热门公司
        };
        
        const res = await getCompanyList(params);
        if (res && res.rows && res.rows.length > 0) {
          // 先创建基础企业数据
          const companies = res.rows.map(company => ({
            id: company.companyId || company.id,
            name: company.companyName || '未知公司',
            logoUrl: company.logoUrl || '/static/images/default-company.png',
            rating: 0, // 将在后面获取
            reviewCount: 0, // 将在后面获取
            tags: company.industryTags ? 
              (Array.isArray(company.industryTags) ? company.industryTags : company.industryTags.split(',')) : 
              ['暂无标签']
          }));
          
          // 为每家公司获取综合评分和评价数量
          for (const company of companies) {
            // 并行获取评分和评价数量
            const [rating, reviewCount] = await Promise.all([
              this.getCompanyRating(company.id),
              this.getCompanyReviewCount(company.id)
            ]);
            
            company.rating = rating || (company.rating || 0);
            company.reviewCount = reviewCount || 0;
          }
          
          this.hotCompanies = companies;
        }
      } catch (error) {
        console.error('加载热门公司失败:', error);
        // 使用默认数据作为降级方案
        this.hotCompanies = [
          {
            id: 1,
            name: '字节跳动',
            logoUrl: '/static/c1.png',
            rating: 4.2,
            reviewCount: 1256,
            tags: ['互联网', '大厂', '加班严重']
          },
          {
            id: 2,
            name: '腾讯科技',
            logoUrl: '/static/c2.png',
            rating: 4.5,
            reviewCount: 2345,
            tags: ['互联网', '大厂', '福利好']
          },
          {
            id: 3,
            name: '阿里巴巴',
            logoUrl: '/static/c3.png',
            rating: 4.3,
            reviewCount: 1890,
            tags: ['电商', '大厂', '氛围好']
          }
        ];
      }
    },
    
    // 加载最新评价
    async loadLatestReviews() {
        try {
          const params = {
            pageNum: 1,
            pageSize: 5
          };
          
          const res = await getUserReviews(params);
		  console.log("companyId:",res.rows[0].companyId)
		  const company= await getCompanyDetail(res.rows[0].companyId)
		  console.log("company:",company.data.companyName)
          if (res && res.rows) {
            // 先设置基础数据
            this.latestReviews = res.rows.map(item => ({
              id: item.id,
              companyName: company.data.companyName || '未知公司',
              userName: item.nickName || '匿名用户',
              userAvatar: item.avatarUrl || '/static/images/default-avatar.png',
              time: item.updatedAt || item.createdAt || '',
              content: item.content || '',
              likes: item.likes || 0,
              comments: item.comments || 0,
              score: 0, // 初始化为0，稍后获取
              dimensions: []
            }));
            
            // 为每个评价获取综合评分
            for (const review of this.latestReviews) {
              const avgScore = await this.getReviewAverageScore(review.id);
              review.score = avgScore;
            }
          }
        } catch (error) {
          console.error('加载最新评价失败:', error);
          // 使用默认数据作为降级方案
          this.latestReviews = [
            {
              id: 1,
              companyName: '字节跳动',
              userName: '匿名用户',
              userAvatar: '/static/images/avatar1.png',
              time: '2023-10-15',
              content: '公司氛围不错，年轻人居多，沟通无障碍。但加班确实比较严重，996是常态，不过薪资给得很到位。',
              likes: 32,
              comments: 5,
              score: 4.0
            }
          ];
        }
      },
    changeSwiper(e) {
      this.current = e.detail.current;
    },
    toSearch() {
      if (this.searchKeyword.trim()) {
        uni.navigateTo({
          url: `/pages/search/search?keyword=${this.searchKeyword}`
        });
      } else {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        });
      }
    },
    toCompanyDetail(companyId) {
      uni.navigateTo({
        url: `/pages/company/detail?id=${companyId}`
      });
    },
    toCompanySearch() {
      uni.switchTab({
        url: '/pages/search/search'
      });
    },
    toAiAssistant() {
      uni.switchTab({
        url: '/pages/ai/assistant'
      });
    },
    toNews() {
      uni.navigateTo({
        url: '/pages/news/list'
      });
    },
    toPublishReview() {
      uni.navigateTo({
        url: '/pages/review/publish'
      });
    },
    toMoreCompanies() {
      uni.navigateTo({
        url: '/pages/company/list'
      });
    },
    toAllReviews() {
      uni.navigateTo({
        url: '/pages/review/list'
      });
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-box {
  display: flex;
  padding: 10px;
  background-color: #fff;
}

.search-input {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20px;
  padding: 8px 15px;
  margin-right: 10px;
}

.search-input input {
  flex: 1;
  margin-left: 5px;
  font-size: 14px;
  color: #333;
}

.search-btn {
  width: 60px;
  height: 36px;
  line-height: 36px;
  background-color: #36D;
  color: #fff;
  border-radius: 20px;
  font-size: 14px;
  padding: 0;
}

.banner {
  width: 100%;
  background-color: #fff;
  padding-bottom: 10px;
}

.swiper {
  width: 100%;
  height: 150px;
}

.banner-img {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.dots {
  margin-top: -25px;
  margin-bottom: 10px;
}

.functions {
  display: flex;
  justify-content: space-around;
  padding: 15px 0;
  background-color: #fff;
  margin-bottom: 10px;
}

.func-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.func-icon {
  margin-bottom: 5px;
}

.func-text {
  font-size: 12px;
  color: #333;
}

.section {
  background-color: #fff;
  margin-bottom: 10px;
  padding: 0 15px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.title-text {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.more {
  font-size: 14px;
  color: #666;
}

.company-list {
  padding: 10px 0;
}

.company-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.company-item:last-child {
  border-bottom: none;
}

.company-logo {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 10px;
}

.company-info {
  flex: 1;
}

.company-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.company-rating {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.rating-num {
  font-size: 14px;
  color: #FF6600;
  margin-left: 3px;
  font-weight: bold;
}

.review-count {
  font-size: 12px;
  color: #999;
  margin-left: 5px;
}

.company-tags {
  display: flex;
  flex-wrap: wrap;
}

.tag {
  font-size: 12px;
  color: #666;
  background-color: #f5f5f5;
  padding: 2px 8px;
  border-radius: 10px;
  margin-right: 5px;
  margin-bottom: 5px;
}

.review-list {
  padding: 10px 0;
}

.review-item {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.review-time {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

.review-content {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 10px;
}

.review-metrics {
  display: flex;
  align-items: center;
}

.metric-item {
  display: flex;
  align-items: center;
  margin-right: 5px;
  font-size: 12px;
  color: #999;
}

.metric-item text {
  margin-left: 3px;
  color: #999;
}
</style>
